<?php
namespace user;
use View;
use Response;
use BaseController;
use Auth;
use User;
use News;
use Input;
use Validator;
use Redirect;

class NewsController extends BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /user/Newss
	 *
	 * @return Response
	 */
	public function index()
	{
		$news = News::where('user_id',Auth::id())->orderBy('created_at','desc')->get();
		return View::make('user.news.index')->with('title','新闻投递')->with('news',$news);
	}

	public function add()
	{
		return View::make('user.news.add')->with('title','新闻投递');
	}

	public function doAdd(){
		$rules = array(
			'type' => 'required|integer',
			'title' => 'required|min:2',
			'content' => 'required',
		);
		
		$validator = Validator::make(Input::all(),$rules);
		if($validator->passes()){
			$news = News::create(Input::only('type','original_url','title','projects_name','content'));
			$news->user_id = Auth::id();
			if($news->save()){
				return Redirect::to('user/news')->with('message',array('type'=>'success','content'=>'新闻投递成功'));
			}else{
				return Redirect::back()->with('message',array('type'=>'danger','content'=>'新闻投递失败'))->withInput();
			}
		}else{
			return Redirect::back()->withInput()->withErrors($validator);
		}
	}


	public function modify($id){
		return View::make('user.News.modify')->with('news',News::find($id))->with('title','投递新闻');
	}

	public function doModify(){
		$rules = array(
			'type' => 'required|integer',
			'title' => 'required|min:2',
			'content' => 'required',
		);
		
		$validator = Validator::make(Input::all(),$rules);
		if($validator->passes()){
			$news = News::find(Input::get('id'));
			$news->title = Input::get('title');
			$news->type = Input::get('type');
			$news->original_url = Input::get('original_url');
			$news->content = Input::get('content');
			$news->projects_name = Input::get('projects_name');
			if($news->save()){
				return Redirect::to('user/news')->with('message',array('type'=>'success','content'=>'修改成功'));
			}else{
				return Redirect::back()->with('message',array('type'=>'danger','content'=>'修改失败'))->withInput();
			}
		}else{
			return Redirect::back()->with('message',array('type'=>'danger','content'=>'修改失败'))->withInput()->withErrors($validator);
		}
	}

	public function delete($id){
		$news = News::find($id);
		if($news && $news->delete()){
			return Redirect::back()->with('message',array('type'=>'danger','content'=>'删除成功'));
		}else{
			return Redirect::back()->with('message',array('type'=>'success','content'=>'删除失败'));
		}
		
	}
}